import { AxiosHeaders } from 'axios';

import { getToken } from '@/utils/auth';
import { getTenantCode } from '@/utils/tenant';

import service from './service';
import setting from './setting';
import { AxiosConfig } from './types';

const { defaultHeader } = setting;

/**
 * 自定义请求函数
 *
 * @param option 自定义的接口调用参数配置对象
 * @returns Promise对象
 */
const request = (option: AxiosConfig) => {
  const { url, method, params, data, responseType, headersType } = option;

  const headers = new AxiosHeaders();
  headers.set('Content-Type', headersType || defaultHeader);
  headers.set('Authorization', getToken() || '');
  headers.set('Tenant', getTenantCode() || '');

  return service.request({
    url,
    method,
    params,
    data,
    responseType,
    headers,
  });
};

export default {
  get: <T = any>(option: AxiosConfig) => {
    return request({ method: 'get', ...option }) as Promise<T>;
  },
  post: <T = any>(option: AxiosConfig) => {
    return request({ method: 'post', ...option }) as Promise<T>;
  },
  cancelRequest: (url: string | string[]) => {
    return service.cancelRequest(url);
  },
  cancelAllRequest: () => {
    return service.cancelAllRequest();
  },
};
